/**
* Copyright (C) 2018-2020
* All rights reserved, Designed By zhanglin
* 注意：
* 本软件为zhanglin开发研制
 */
package model

import (
	"fmt"
	"github.com/jinzhu/gorm"
	"shop/global"
	"time"
)

type IUser interface {
	InsertUser() (int64, error)
	DeleteUser(id int64) error
	UpdateUser() error
	FindUserList() (interface{}, error)
	SplitPageUserList(pageIndex int64, pageSize int64) (interface{}, error)
	LoginByUsernameAndPassword() (string, error)
}

/**
	User实体对象
 **/
type User struct {
	Id int64 `json:"id" gorm:"primary_key"` //ID

	AvatarId int64 `json:"avatar_id"` //头像

	Email string `json:"email"` //邮箱

	Enabled int64 `json:"enabled"` //状态：1启用、0禁用

	Password string `json:"password"` //密码

	Username string `json:"username"` //用户名

	DeptId int64 `json:"dept_id"` //部门名称

	Phone string `json:"phone"` //手机号码

	JobId int64 `json:"job_id"` //岗位名称

	CreateTime time.Time `json:"create_time"` //创建日期

	LastPasswordResetTime time.Time `json:"last_password_reset_time"` //最后修改密码的日期

	NickName string `json:"nick_name"` //

	Sex string `json:"sex"` //
}

type LoginUser struct {
	UserInfo   User
	Permission []string `json:"permission"` // 角色组
	Token      string   `json:"token"`      // token

}

func (vo *User) InsertUser() (int64, error) {
	table := global.GDB.Table("user")
	if err := table.Create(&vo).Error; err != nil {
		return 0, err
	}

	return vo.Id, nil
}

func (vo *User) DeleteUser(id int64) error {
	table := global.GDB.Table("user")
	table = table.Where("id = ?", id)
	if err := table.Delete(User{}).Error; err != nil {
		return err
	}
	return nil
}

func (vo *User) UpdateUser() error {

	table := global.GDB.Table("user")
	table = table.Where("id = ?", vo.Id)
	if err := table.Updates(map[string]interface{}{
		"id": vo.Id, "avatar_id": vo.AvatarId, "email": vo.Email, "enabled": vo.Enabled, "password": vo.Password, "username": vo.Username, "dept_id": vo.DeptId, "phone": vo.Phone, "job_id": vo.JobId, "create_time": vo.CreateTime, "last_password_reset_time": vo.LastPasswordResetTime, "nick_name": vo.NickName, "sex": vo.Sex}).Error; err != nil {
		return err
	}
	return nil
}

func (vo *User) FindUserList() ([]User, error) {
	var lists []User
	table := global.GDB.Table("user")
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}
	return lists, nil
}

func (vo *User) SplitPageUserList(pageIndex int64, pageSize int64) (interface{}, error) {
	var lists []User
	var total int64
	table := global.GDB.Table("user")
	table = table.Select("  id,   avatar_id,   email,   enabled,   password,   username,   dept_id,   phone,   job_id,   create_time,   last_password_reset_time,   nick_name,   sex   ")
	if err := table.Count(&total).Error; err != nil {
		return lists, err
	}
	table = table.Offset((pageIndex - 1) * pageSize).Limit(pageSize)
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}

	m := make(map[string]interface{})
	m["lists"] = lists
	m["total"] = total
	return m, nil
}

func (vo *User) LoginByUsernameAndPassword() (string, error) {
	var loginUser LoginUser
	loginUser, err := getUserByUsername(vo.Username)
	if err != nil {
		fmt.Println(loginUser)
	}

	return "", nil
}

func findRoleByUserIdList(userId int64) ([]Role, error) {
	var lists []Role

	table := global.GDB.Table("role r").Joins("LEFT JOIN users_roles ur ON ur.role_id = r.id ").Where("ur.user_id = ?", userId)
	table = table.Select(" r.* ")
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}
	return lists, nil
}

func findMenuByRoleIdList(roleId int64) ([]Menu, error) {
	var lists []Menu
	table := global.GDB.Table("menu r").Joins("LEFT JOIN roles_menus ur ON ur.menu_id = r.id ").Where("ur.role_id = ?", roleId)
	table = table.Select(" r.* ")
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}
	return lists, nil
}

func findDeptByRoleIdList(roleId int64) ([]Dept, error) {
	var lists []Dept
	table := global.GDB.Table("dept r").Joins("LEFT JOIN roles_depts ur ON ur.dept_id = r.id ").Where("ur.role_id = ?", roleId)
	table = table.Select(" r.* ")
	if err := table.Find(&lists).Error; err != nil {
		return lists, err
	}
	return lists, nil
}

// 根据用户名称查询用户信息
func getUserByUsername(userName string) (LoginUser, error) {
	var loginUser LoginUser
	var user User
	var roles []Role
	table := global.GDB.Table("user").Where("username = ?", userName)
	if err := table.Select(" id,   avatar_id,   email,   enabled,   password,   username,   dept_id,   phone,   job_id,   create_time,   last_password_reset_time,   nick_name,   sex   ").First(&user).Error; err != nil {
		// 判断错误
		switch {
		case err == gorm.ErrRecordNotFound:
			// 说明没有找到
			return loginUser, nil
		case err != nil:
			return loginUser, err
		}
	}
	loginUser.UserInfo = user
	roles, err := findRoleByUserIdList(user.Id)
	if err != nil {
		return loginUser, err
	}

	var permission []string
	for i := 0; i < len(roles); i++ {
		var m []Menu
		m, _ = findMenuByRoleIdList(roles[i].Id)
		for _, v := range m {
			if v.Permission != "" {
				permission = append(permission, v.Permission)
			}

		}
	}
	loginUser.Permission = permission
	return loginUser, nil
}
